package com.anda.jsu.yangsp.core.view.util;

import java.io.UnsupportedEncodingException;

/**
 * 转换字符编码
 * 
 * @author xiaolu
 * @since 2012-12-06
 * 
 */
public class ConvertCharacterEcoding {

	public static String convertIsoToUtf(String name)
			throws UnsupportedEncodingException {
		return new String(name.getBytes("ISO-8859-1"), "utf-8");
	}

	public static String convertUtfToIso(String name)
			throws UnsupportedEncodingException {
		return new String(name.getBytes("utf-8"), "ISO-8859-1");
	}

	public static String convertGbToIso(String name)
			throws UnsupportedEncodingException {
		// return URLEncoder.encode(fileName, "UTF-8"))//等价语句
		return new String(name.getBytes("Gb2312"), "ISO-8859-1");
	}

	public static String convertGbToUtf(String fileName)
			throws UnsupportedEncodingException {
		return new String(fileName.getBytes("Gb2312"), "UTF-8");
	}

	/**
	 * 中文转码
	 * 
	 * @param source
	 * @return
	 */
	public static String unescape(String source) {
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(source.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < source.length()) {
			pos = source.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (source.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(source.substring(pos + 2,
							pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(source.substring(pos + 1,
							pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(source.substring(lastPos));
					lastPos = source.length();
				} else {
					tmp.append(source.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

}
